import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ValueListenableBuilerDemo(),
    );
  }
}

class ValueListenableBuilerDemo extends StatefulWidget {
  @override
  _ValueListenableBuilerDemoState createState() =>
      _ValueListenableBuilerDemoState();
}

class _ValueListenableBuilerDemoState extends State<ValueListenableBuilerDemo> {
  @override
  Widget build(BuildContext context) {
    print("界面重建");
    return ChangeNotifierProvider(
      create: (_) => _Counter(),
      child: Column(
        children: [
          Consumer(
            builder: (
              BuildContext context,
              _Counter value,
              Widget? child,
            ) {
              print("Consumer 重建");
              return Text("Consumer 改变后 value=${value._num}");
            },
          ),
          Selector(
              builder: (context, value, child) {
                print("Selector 重建");
                 return Text("Selector 改变后 value=${value}");
              },
              selector: (_, _Counter c){
                 return c._num;
              }),
          TextView(),
          Btn()
        ],
      ),
    );
  }
}

class TextView extends StatefulWidget {
  @override
  _TextViewState createState() => _TextViewState();
}

class _TextViewState extends State<TextView> {
  @override
  Widget build(BuildContext context) {
    print("TextView 重建");
    var select = context.select((_Counter value) => value._num);
    return Container(child:
       Text("context.select 改变后 value= ${select}"),);
  }
}


class Btn extends StatefulWidget {
  @override
  _BtnState createState() => _BtnState();
}

class _BtnState extends State<Btn> {
  @override
  Widget build(BuildContext context) {
    print("Btn 重建");
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
      child: ElevatedButton(
          onPressed: () {
            // Provider.of<_Counter>(context,listen: false).addNum();
            context.read<_Counter?>()?.addNum();
          },
          child: Text("点我看看")),
    );
  }
}

class _Counter with ChangeNotifier, DiagnosticableTreeMixin {
  int _num = 0;

  int get num => _num;

  void addNum() {
    _num++;
    notifyListeners();
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(IntProperty("_num", _num));
  }
}
